package com.ruoyi.leave.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.obs.services.internal.ServiceException;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.CommonResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.Arith;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.leave.domain.WorkflowWaterPlanAdjust;
import com.ruoyi.leave.mapper.WorkflowWaterPlanAdjustMapper;
import com.ruoyi.leave.service.IWorkflowWaterPlanAdjustService;
import com.ruoyi.leave.util.WorkFlowCache;
import com.ruoyi.leave.util.WorkFlowConstants;
import com.ruoyi.manage.domain.*;
import com.ruoyi.manage.domain.dto.*;
import com.ruoyi.manage.service.*;
import com.ruoyi.system.service.ISysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.constant.CommonResult.EXAMINE_TYPE.BESUBMITTED;

/**
 * 用水计划调整Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-12
 */
@Service
@Slf4j
public class WorkflowWaterPlanAdjustServiceImpl implements IWorkflowWaterPlanAdjustService {
    @Resource
    private WorkflowWaterPlanAdjustMapper workflowWaterPlanAdjustMapper;
    @Autowired
    private ProcessRuntime processRuntime;

    @Autowired
    private TaskService taskService;

    @Resource
    private DynamicJumpService dynamicJumpService;

    @Autowired
    private WorkFlowCache workFlowCache;

    @Autowired
    private ISwWaterAdjustLogService swWaterAdjustLogService;

    @Autowired
    private IBtSwUnitService btSwUnitService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private IBsSwQuotaIndustryService swQuotaIndustryService;

    @Autowired
    private ISwWaterAdjustDetailService swWaterAdjustDetailService;

    @Autowired
    private ISwWaterAdjustAnnualService swWaterAdjustAnnualService;

    @Autowired
    private ISwWaterAdjustMonthlyService swWaterAdjustMonthlyService;

    @Autowired
    private ISwWaterAdjustAgricultureDetailService swWaterAdjustAgricultureDetailService;

    /**
     * 查询用水计划调整
     *
     * @param id 用水计划调整ID
     * @return 用水计划调整
     */
    @Override
    public WorkflowWaterPlanAdjust selectWorkflowWaterPlanAdjustById(String id) {
        return workflowWaterPlanAdjustMapper.selectWorkflowWaterPlanAdjustById(id);
    }

    /**
     * 查询用水计划调整列表
     *
     * @param workflowWaterPlanAdjust 用水计划调整
     * @return 用水计划调整
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "wwpa")
    public List<WorkflowWaterPlanAdjust> selectWorkflowWaterPlanAdjustList(WorkflowWaterPlanAdjust workflowWaterPlanAdjust) {
        List<WorkflowWaterPlanAdjust> waterPlanAdjustList = workflowWaterPlanAdjustMapper.selectWorkflowWaterPlanAdjustList(workflowWaterPlanAdjust);
        List<WorkflowWaterPlanAdjust> resworkflowWaterAdjust = new ArrayList<>();
        if(waterPlanAdjustList != null && !waterPlanAdjustList.isEmpty()){
            /**
             * 单位信息
             */
            List<BtSwUnit> unitList = btSwUnitService.selectBtSwUnitList(new BtSwUnit());
            Map<Long, BtSwUnit> unitMap = new HashMap<>();
            if (unitList != null && !unitList.isEmpty()) {
                unitMap = unitList.stream().collect(Collectors.toMap(BtSwUnit::getId, a -> a, (k1, k2) -> k1));
            }

            /**
             * 机构信息
             */
            List<SysDept> sysDeptList = sysDeptService.selectDeptList(new SysDept());
            Map<Long, SysDept> deptMap = new HashMap<>();
            if (sysDeptList != null && !sysDeptList.isEmpty()) {
                deptMap = sysDeptList.stream().collect(Collectors.toMap(SysDept::getDeptId, a -> a, (k1, k2) -> k1));
            }
            for (WorkflowWaterPlanAdjust adjust : waterPlanAdjustList) {
                if (CommonResult.PLAN_TYPE.INDUSTRY.getValue().equals(adjust.getType())) {
                    // 用水单位
                    BtSwUnit swUnit = unitMap.get(adjust.getUnitId());
                    if (swUnit != null) {
                        adjust.setUnitCode(swUnit.getUnitCode()); // 单位代码
                        adjust.setUnitName(swUnit.getUnitName()); // 单位名称
                        adjust.setContacts(swUnit.getContacts()); // 联系人
                        adjust.setTel(swUnit.getTel()); // 联系方式
                    }
                } else {
                    SysDept sysDept = deptMap.get(adjust.getDeptId());
                    if (sysDept != null) {
                        adjust.setUnitName(sysDept.getDeptName()); // 机构名称
                        adjust.setContacts(sysDept.getLeader()); // 联系人
                        adjust.setTel(sysDept.getPhone()); // 联系方式
                    }
                }
                List<String> userRoles = SecurityUtils.getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toList());
                String processDefinitionKey = WorkFlowConstants.WATER_PLAN_CHANNEL.getEnum(adjust.getChannel(), "adjust").getName();
                String waterPlanProcessDefinitionId = workFlowCache.getWaterPlanProcessDefinitionId(adjust.getInstanceId(), processDefinitionKey);
                Collection<FlowElement> waterPlanFlowElementList = workFlowCache.getWaterPlanFlowElementList(waterPlanProcessDefinitionId);
                if(null == waterPlanFlowElementList){
                    continue;
                }
                int currentUserRoleSeq = 0, dbUserRoleSeq = 0, i = 0;
                Iterator<FlowElement> iterator = waterPlanFlowElementList.iterator();
                while (iterator.hasNext()) {
                    i++;
                    FlowElement flowElement = iterator.next();
                    if (flowElement instanceof UserTask) {
                        UserTask userTask = (UserTask) flowElement;
                        if (CollUtil.containsAny(userTask.getCandidateGroups(), userRoles)) {
                            currentUserRoleSeq = i;
                        }
                        if (CollUtil.containsAny(userTask.getCandidateGroups(), StrUtil.split(adjust.getRolegroup(), ","))) {
                            dbUserRoleSeq = i;
                        }
                    }
                }
                int diffSeq = currentUserRoleSeq - dbUserRoleSeq;
                // 查询待提交
                if ("1".equals(workflowWaterPlanAdjust.getReviewStatus()) && diffSeq == 0 && !"9".equals(adjust.getState())) {
                    adjust.setStatus("1");
                    resworkflowWaterAdjust.add(adjust);
                } else if ("2".equals(workflowWaterPlanAdjust.getReviewStatus())) {
                    if ("9".equals(adjust.getState())) {
                        adjust.setStatus("2");
                    } else {
                        if (diffSeq <= -1) {
                            adjust.setStatus("2");
                        } else {
                            continue;
                        }
                    }
                    resworkflowWaterAdjust.add(adjust);
                } else if ("3".equals(workflowWaterPlanAdjust.getReviewStatus())) {
                    if ("9".equals(adjust.getState())) {
                        adjust.setStatus("2");
                    } else {
                        if (diffSeq == 0) {
                            adjust.setStatus("1");
                        } else if (diffSeq <= -1) {
                            adjust.setStatus("2");
                        } else {
                            continue;
                        }
                    }
                    resworkflowWaterAdjust.add(adjust);
                }
            }
        }
        return resworkflowWaterAdjust;
    }

    /**
     * 新增用水计划调整
     *
     * @param workflowWaterPlanAdjust 用水计划调整
     * @return 结果
     */
    @Override
    public int insertWorkflowWaterPlanAdjust(WorkflowWaterPlanAdjust workflowWaterPlanAdjust) {
        SwWaterAdjustLog swWaterAdjustLog = swWaterAdjustLogService.selectSwWaterAdjustLogById(workflowWaterPlanAdjust.getPlanId());
        // 申请渠道 1：农业  2：非农
        if("0".equals(swWaterAdjustLog.getType())){
            workflowWaterPlanAdjust.setChannel("2");
        } else {
            workflowWaterPlanAdjust.setChannel("1");
        }
        swWaterAdjustLog.setStatus(BESUBMITTED.getValue());
        swWaterAdjustLogService.updateSwWaterAdjustLogDto(swWaterAdjustLog);
        String id = UUID.randomUUID().toString();
        workflowWaterPlanAdjust.setId(id);
        workflowWaterPlanAdjust.setCreateTime(DateUtils.getNowDate());
        workflowWaterPlanAdjust.setPlanId(workflowWaterPlanAdjust.getPlanId());
        workflowWaterPlanAdjust.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId());
        ProcessInstance processInstance = startProcess(workflowWaterPlanAdjust);
        List<String> userRoles = SecurityUtils.getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        String processDefinitionKey = WorkFlowConstants.WATER_PLAN_CHANNEL.getEnum(workflowWaterPlanAdjust.getChannel(), "adjust").getName();
        Task firstUserTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskCandidateGroupIn(userRoles)
                .processDefinitionKey(processDefinitionKey).singleResult();
        taskService.claim(firstUserTask.getId(), SecurityUtils.getLoginUser().getUsername());
        taskService.setAssignee(firstUserTask.getId(), SecurityUtils.getLoginUser().getUsername());
        taskService.setVariableLocal(firstUserTask.getId(), "userName", SecurityUtils.getLoginUser().getUsername());
        taskService.setVariableLocal(firstUserTask.getId(), "depId", SecurityUtils.getLoginUser().getUser().getDeptId());
        taskService.complete(firstUserTask.getId());
        Map<String, UserTask> userTaskList = workFlowCache.getUserTaskList(processInstance.getProcessDefinitionId());
        workflowWaterPlanAdjust.setRolegroup(userTaskList.get(firstUserTask.getTaskDefinitionKey()).getFormKey().split("#")[1]);
        workflowWaterPlanAdjust.setInstanceId(processInstance.getId());
        workflowWaterPlanAdjust.setState(WorkFlowConstants.WATER_PLAN_STATUS_ENUM.INIT.getValue());
        workflowWaterPlanAdjust.setCreateName(SecurityUtils.getNickName());
        workflowWaterPlanAdjust.setCreateBy(SecurityUtils.getUsername());
        workflowWaterPlanAdjust.setCreateTime(DateUtils.getNowDate());
        return workflowWaterPlanAdjustMapper.insertWorkflowWaterPlanAdjust(workflowWaterPlanAdjust);
    }

    /**
     * 修改用水计划调整
     *
     * @param workflowWaterPlanAdjust 用水计划调整
     * @return 结果
     */
    @Override
    public int updateWorkflowWaterPlanAdjust(WorkflowWaterPlanAdjust workflowWaterPlanAdjust) {
        workflowWaterPlanAdjust.setUpdateTime(DateUtils.getNowDate());
        return workflowWaterPlanAdjustMapper.updateWorkflowWaterPlanAdjust(workflowWaterPlanAdjust);
    }

    /**
     * 批量删除用水计划调整
     *
     * @param ids 需要删除的用水计划调整ID
     * @return 结果
     */
    @Override
    public int deleteWorkflowWaterPlanAdjustByIds(String[] ids) {
        return workflowWaterPlanAdjustMapper.deleteWorkflowWaterPlanAdjustByIds(ids);
    }

    /**
     * 删除用水计划调整信息
     *
     * @param id 用水计划调整ID
     * @return 结果
     */
    @Override
    public int deleteWorkflowWaterPlanAdjustById(String id) {
        return workflowWaterPlanAdjustMapper.deleteWorkflowWaterPlanAdjustById(id);
    }

    private ProcessInstance startProcess(WorkflowWaterPlanAdjust workflowWaterPlanAdjust) {
        Map<String, Object> processVariableMap = new HashMap<>();
        processVariableMap.put("planId", workflowWaterPlanAdjust.getPlanId());
        processVariableMap.put("workflowWaterPlanId", workflowWaterPlanAdjust.getId());
        processVariableMap.put("channel", workflowWaterPlanAdjust.getChannel());
        processVariableMap.put("startDepId", SecurityUtils.getLoginUser().getUser().getDeptId());
        String processDefinitionKey = WorkFlowConstants.WATER_PLAN_CHANNEL.getEnum(workflowWaterPlanAdjust.getChannel(), "adjust").getName();
        processVariableMap.put("key", processDefinitionKey);
        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                .start()
                .withProcessDefinitionKey(processDefinitionKey)
                .withBusinessKey(workflowWaterPlanAdjust.getId())
                .withVariables(processVariableMap)
                .withName(Objects.requireNonNull(WorkFlowConstants.WATER_PLAN_CHANNEL.getEnum(workflowWaterPlanAdjust.getChannel(), "adjust")).getLabel())
                .build());
        return processInstance;
    }

    @Override
    public void claimTask(WorkflowWaterPlanAdjust workflowWaterPlanAdjust) {
        List<String> roles = StrUtil.split(workflowWaterPlanAdjust.getRolegroup(), ",");
        Task task = taskService.createTaskQuery().processInstanceId(workflowWaterPlanAdjust.getInstanceId()).singleResult();
        String username = SecurityUtils.getUsername();
        if (Objects.isNull(task)) {
            log.info("{}没找到可以拾取的任务", username);
        }
        taskService.claim(task.getId(), username);
        workflowWaterPlanAdjust.setAssignee(username);
        workflowWaterPlanAdjust.setState(WorkFlowConstants.WATER_PLAN_STATUS_ENUM.WAIT_CHECK.getValue());
        workflowWaterPlanAdjust.setUpdateTime(new Date());
        workflowWaterPlanAdjust.setUpdateBy(username);
        workflowWaterPlanAdjustMapper.updateWorkflowWaterPlanAdjust(workflowWaterPlanAdjust);
    }

    @Override
    public void unClaimTask(WorkflowWaterPlanAdjust workflowWaterPlanAdjust) {
        List<String> roles = StrUtil.split(workflowWaterPlanAdjust.getRolegroup(), ",");
        String username = SecurityUtils.getUsername();
        Task task = taskService.createTaskQuery().processInstanceId(workflowWaterPlanAdjust.getInstanceId()).singleResult();
        if (Objects.isNull(task)) {
            log.info("{}没找到可以归还的任务", username);
            return;
        }
        taskService.unclaim(task.getId());
        workflowWaterPlanAdjust.setAssignee(null);
        workflowWaterPlanAdjust.setState(WorkFlowConstants.WATER_PLAN_STATUS_ENUM.WAIT_CHECK.getValue());
        workflowWaterPlanAdjust.setUpdateTime(new Date());
        workflowWaterPlanAdjust.setUpdateBy(username);
        workflowWaterPlanAdjustMapper.updateWorkflowWaterPlanAdjust(workflowWaterPlanAdjust);
    }

    @Override
    public void completeTask(WorkflowWaterPlanAdjust workflowWaterPlanAdjust) {
        String username = SecurityUtils.getUsername();
        Task task = taskService.createTaskQuery().taskAssignee(username).processInstanceId(workflowWaterPlanAdjust.getInstanceId()).singleResult();
        if (Objects.isNull(task)) {
            log.info("{}没找到可以通过的任务", username);
        }
        taskService.setVariableLocal(task.getId(), "userName", SecurityUtils.getLoginUser().getUsername());
        taskService.setVariableLocal(task.getId(), "depId", SecurityUtils.getLoginUser().getUser().getDeptId());
        taskService.setVariableLocal(task.getId(), "comment", workflowWaterPlanAdjust.getComment());
        taskService.complete(task.getId());
        workflowWaterPlanAdjust.setAssignee(null);

        List<String> formKeyStrList = StrUtil.split(task.getFormKey(), "#");
        String nextRoleGroup = formKeyStrList.get(1);
        if (StringUtils.isEmpty(nextRoleGroup)) {
            workflowWaterPlanAdjust.setState(WorkFlowConstants.WATER_PLAN_STATUS_ENUM.FINISH.getValue());
        }
        workflowWaterPlanAdjust.setActivitiname(task.getName());
        workflowWaterPlanAdjust.setRolegroup(nextRoleGroup);
        workflowWaterPlanAdjust.setUpdateTime(new Date());
        workflowWaterPlanAdjust.setUpdateBy(username);
        workflowWaterPlanAdjustMapper.updateWorkflowWaterPlanAdjust(workflowWaterPlanAdjust);
    }

    @Override
    public void rejectTask(WorkflowWaterPlanAdjust workflowWaterPlanAdjust) {
        String username = SecurityUtils.getUsername();
        List<String> roles = StrUtil.split(workflowWaterPlanAdjust.getRolegroup(), ",");
        Task task = taskService.createTaskQuery().taskCandidateGroupIn(roles).processInstanceId(workflowWaterPlanAdjust.getInstanceId()).singleResult();
        if (Objects.isNull(task)) {
            log.info("{}没找到可以拒绝的任务", username);
        }
        List<String> formKeyStrList = StrUtil.split(task.getFormKey(), "#");
        String fromAcitivitiId = task.getTaskDefinitionKey(),
                toActivitiId = formKeyStrList.get(2);
        taskService.setVariableLocal(task.getId(), "userName", SecurityUtils.getLoginUser().getUsername());
        taskService.setVariableLocal(task.getId(), "depId", SecurityUtils.getLoginUser().getUser().getDeptId());
        dynamicJumpService.execution(workflowWaterPlanAdjust.getInstanceId(), fromAcitivitiId, toActivitiId);
        workflowWaterPlanAdjust.setAssignee(null);
        String backRoleGroup = formKeyStrList.get(0);
        if (StringUtils.isNotEmpty(backRoleGroup)) {
            workflowWaterPlanAdjust.setRolegroup(backRoleGroup);
        }
        workflowWaterPlanAdjust.setRolegroup(backRoleGroup);
        workflowWaterPlanAdjust.setState(WorkFlowConstants.WATER_PLAN_STATUS_ENUM.REJECT.getValue());
        workflowWaterPlanAdjust.setUpdateTime(new Date());
        workflowWaterPlanAdjust.setUpdateBy(username);
        workflowWaterPlanAdjustMapper.updateWorkflowWaterPlanAdjust(workflowWaterPlanAdjust);
    }

    @Override
    public int completeTaskByPlanID(Long planId) {
        WorkflowWaterPlanAdjust workflowWaterPlanAdjust = new WorkflowWaterPlanAdjust();
        workflowWaterPlanAdjust.setPlanId(planId);
        List<WorkflowWaterPlanAdjust> workflowWaterPlanAdjustList = workflowWaterPlanAdjustMapper.selectWorkflowWaterPlanAdjustList(workflowWaterPlanAdjust);
        if (CollectionUtil.isEmpty(workflowWaterPlanAdjustList)) {
            throw new CustomException("没找到可以审核的任务");
        }
        workflowWaterPlanAdjust = workflowWaterPlanAdjustList.get(0);
        if (WorkFlowConstants.WATER_PLAN_STATUS_ENUM.FINISH.getValue().equals(workflowWaterPlanAdjust.getState())) {
            throw new CustomException("已经结束的任务不可以审核");
        }
        claimTask(workflowWaterPlanAdjust);
        completeTask(workflowWaterPlanAdjust);
        return 1;
    }

    @Override
    public int rejectTaskByPlanID(Plan plan) {
        WorkflowWaterPlanAdjust workflowWaterPlanAdjust = new WorkflowWaterPlanAdjust();
        workflowWaterPlanAdjust.setPlanId(plan.getId());
        List<WorkflowWaterPlanAdjust> workflowWaterPlanAdjustList = workflowWaterPlanAdjustMapper.selectWorkflowWaterPlanAdjustList(workflowWaterPlanAdjust);
        if (CollectionUtil.isEmpty(workflowWaterPlanAdjustList)) {
            throw new CustomException("没找到可以拒绝的任务");
        }
        workflowWaterPlanAdjust = workflowWaterPlanAdjustList.get(0);
        workflowWaterPlanAdjust.setComment(plan.getReason());
        if (WorkFlowConstants.WATER_PLAN_STATUS_ENUM.FINISH.getValue().equals(workflowWaterPlanAdjust.getState())) {
            throw new CustomException("已经结束的任务不可以驳回");
        }
        unClaimTask(workflowWaterPlanAdjust);
        rejectTask(workflowWaterPlanAdjust);
        return 1;
    }


    /**
     * 审批(工业)
     *
     * @param plan
     * @return
     */
    @Override
    public int examineIndustryAdjust(Plan plan) {
        int index = 0;
        /**
         * 用水计划产品明细对象
         */
        List<PlanDetail> planDetailList = plan.getPlanDetailList();
        if(planDetailList != null && !planDetailList.isEmpty()){
            /**
             * 定额信息
             */
            List<BsSwQuotaIndustry> quotaList = swQuotaIndustryService.selectBsSwQuotaIndustryList(new BsSwQuotaIndustry());
            Map<Long, BsSwQuotaIndustry> quotaMap = new HashMap<>();
            if(quotaList != null && !quotaList.isEmpty()){
                quotaMap = quotaList.stream().collect(Collectors.toMap(BsSwQuotaIndustry::getId, a -> a, (k1, k2) -> k1));
            }
            // 计划年取水量
            double planWater = 0D;
            for(PlanDetail planDetail : planDetailList){
                BsSwQuotaIndustry industry = quotaMap.get(planDetail.getQuotaId());
                double ratio  = 1D;
                // 先判断是否存在等效配置系数
                if(null != industry.getMaxRatio() && null != industry.getMinRatio()){
                    if((planDetail.getRatio().compareTo(industry.getMaxRatio()) < 0
                            && planDetail.getRatio().compareTo(industry.getMinRatio()) > 0)
                            || planDetail.getRatio().compareTo(industry.getMaxRatio()) == 0
                            || planDetail.getRatio().compareTo(industry.getMinRatio()) == 0){
                        ratio =  planDetail.getRatio();
                    }else {
                        throw new ServiceException("行业代码为"+planDetail.getIndustryCode()+"审批系数不在设置系数的范围");
                    }
                }
                Double quota = Arith.div(planDetail.getExamineWaterConsumption(), planDetail.getExamineNum());
                // 调整的定额 （定额 * 调整系数）
                Double waterQuota = Arith.mul(ratio,planDetail.getWaterQuota());
                if(quota.compareTo(waterQuota) < 0
                        || quota.compareTo(waterQuota) == 0){
                    planWater = Arith.add(planWater,planDetail.getExamineWaterConsumption());
                }else {
                    throw new ServiceException("行业代码为"+planDetail.getSubType()+"审批用水量大于设置定额");
                }
            }

            SwWaterAdjustLog swWaterAdjustLog = new SwWaterAdjustLog();
            swWaterAdjustLog.setApproveWater(planWater);
            swWaterAdjustLog.setId(plan.getAdjustId());
            swWaterAdjustLog.setPlanId(plan.getId());
            if("2".equals(plan.getAdjustType())){
                swWaterAdjustLog.setStatus("2");
            }
            index = swWaterAdjustLogService.updateSwWaterAdjustLogDto(swWaterAdjustLog);
            for(PlanDetail planDetail : planDetailList){
                SwWaterAdjustDetail swWaterAdjustDetail = new SwWaterAdjustDetail();
                BeanUtils.copyProperties(planDetail,swWaterAdjustDetail);
                swWaterAdjustDetailService.updateSwWaterAdjustDetail(swWaterAdjustDetail);
            }
            /**
             * 月份计划
             */
            List<PlanNonfarmMonthly> planNonfarmMonthlyList = plan.getPlanNonfarmMonthlyList();
            if(planNonfarmMonthlyList != null && !planNonfarmMonthlyList.isEmpty()){
                if ("1".equals(plan.getAdjustType())) {
                    swWaterAdjustMonthlyService.examineAdjustMonthly(planNonfarmMonthlyList,swWaterAdjustLog,CommonResult.PLAN_TYPE.INDUSTRY.getValue());
                }else {
                    swWaterAdjustMonthlyService.examineMonthlyAdjustment(planNonfarmMonthlyList,swWaterAdjustLog,CommonResult.PLAN_TYPE.INDUSTRY.getValue());
                }
            }
            /**
             * 年度计划
             */
            List<PlanNonfarmAnnual> planNonfarmAnnualList = plan.getPlanNonfarmAnnualList();
            if(planNonfarmAnnualList != null && !planNonfarmAnnualList.isEmpty()){
                swWaterAdjustAnnualService.examineAdjustAnnual(planNonfarmAnnualList,swWaterAdjustLog);
            }
        }
        return index;
    }

    /**
     * 审批(农业)
     *
     * @param plan
     * @return
     */
    @Override
    public int examineAgricultureAdjust(Plan plan) {
        int index = 0;
        /**
         * 用水计划产品明细对象
         */
        List<SwWaterAdjustAgricultureDetail> agricultureDetailList = plan.getAdjustAgricultureDetailList();
        if(agricultureDetailList != null && !agricultureDetailList.isEmpty()){
            // 计划年取水量
            double planWater = 0D;
            for(SwWaterAdjustAgricultureDetail agricultureDetail : agricultureDetailList){
                Double quota = 0D;
                if("6".equals(agricultureDetail.getType())){
                    if(null != agricultureDetail.getExamineNum() && null != agricultureDetail.getExamineWater50()){
                        quota = Arith.div(Arith.mul(agricultureDetail.getExamineNum(), agricultureDetail.getExamineWater50()),plan.getCoefficient(),5);
                    }
                }else {
                    quota = Arith.div(Arith.mul( agricultureDetail.getExamineArea(),agricultureDetail.getExamineWater50()),plan.getCoefficient(),5);
                }
                Double waterConsumption = Arith.add(agricultureDetail.getExamineSurfaceWater(),agricultureDetail.getExamineGroundWater());
                if(quota.compareTo(waterConsumption) > 0
                        || quota.compareTo(waterConsumption) == 0){
                    planWater = Arith.add(planWater,quota);
                }else {
                    throw new ServiceException("作物为"+agricultureDetail.getCropName()+"上报用水量大于设置定额");
                }
            }
            SwWaterAdjustLog swWaterAdjustLog = new SwWaterAdjustLog();
            swWaterAdjustLog.setApproveWater(planWater);
            swWaterAdjustLog.setId(plan.getAdjustId());
            swWaterAdjustLog.setPlanId(plan.getId());
            if("2".equals(plan.getAdjustType())){
                swWaterAdjustLog.setStatus("2");
            }
            index = swWaterAdjustLogService.updateSwWaterAdjustLogDto(swWaterAdjustLog);
            for(SwWaterAdjustAgricultureDetail agricultureDetail : agricultureDetailList){
                swWaterAdjustAgricultureDetailService.updateSwWaterAdjustAgricultureDetail(agricultureDetail);
            }
            /**
             * 月份计划
             */
            List<PlanNonfarmMonthly> planNonfarmMonthlyList = plan.getPlanNonfarmMonthlyList();
            if(planNonfarmMonthlyList != null && !planNonfarmMonthlyList.isEmpty()){
                if ("1".equals(plan.getAdjustType())) {
                    swWaterAdjustMonthlyService.examineAdjustMonthly(planNonfarmMonthlyList,swWaterAdjustLog,CommonResult.PLAN_TYPE.AGRICULTURE.getValue());
                }else {
                    swWaterAdjustMonthlyService.examineMonthlyAdjustment(planNonfarmMonthlyList,swWaterAdjustLog,CommonResult.PLAN_TYPE.AGRICULTURE.getValue());
                }
            }
            /**
             * 年度计划
             */
            List<PlanAgricultureAnnual> planAgricultureAnnualList = plan.getPlanAgricultureAnnualList();
            if(planAgricultureAnnualList != null && !planAgricultureAnnualList.isEmpty()){
                swWaterAdjustAnnualService.examineAdjustAgricultureAnnual(planAgricultureAnnualList,swWaterAdjustLog);
            }
        }
        return index;
    }
}
